<template>
<section>
  <!--工具条-->
  <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
    <el-form :inline="true">
      <el-form-item>
        <el-select v-model="value" :placeholder="$t('message.select')">
          <el-option
              v-for="(item, idx) in coinType"
              :key="idx"
              :label="item"
              :value="item">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" v-on:click="addRobot">{{$t('message.add-robot')}}</el-button>
      </el-form-item>
    </el-form>
  </el-col>

  <!--列表-->
  <el-table
      v-loading="dataTableVisible"
      :data="tableData"
      style="width: 100%">
    <el-table-column
        prop="robot_id"
        :label="$t('message.robot-id')" width="150">
    </el-table-column>
    <el-table-column
        prop="symbol"
        :label="$t('message.pair-name')" width="180">
    </el-table-column>
    <el-table-column
        prop="status"
        :label="$t('message.status')" width="150">
      <template slot-scope="scope">
        <span v-if="scope.row.status === '服务异常'">{{$t('message.service-exceptions')}}</span>
        <span v-else-if="scope.row.status === '开启'">{{$t('message.enabled')}}</span>
        <span v-else>{{$t('message.close')}}</span>
      </template>
    </el-table-column>
    <el-table-column
        prop="created_at"
        :label="$t('message.create-time')">
    </el-table-column>
    <el-table-column
        prop="detail"
        :label="$t('message.operation')">
      <template slot-scope="scope">
        <el-button @click="openDetail(scope.row.robot_id, scope.row.type, scope.row.symbol)" type="text" size="small">{{$t('message.detail')}}</el-button>
        <el-button @click="openRobotStart(scope.row.robot_id, scope.row.type, scope.row.status)" type="text" size="small">{{scope.row.status === '开启' ? $t('message.stop') : $t('message.open')}}</el-button>
        <el-button @click="openRobotDelete(scope.row.robot_id, scope.row.type)" type="text" size="small">{{$t('message.delete')}}</el-button>
        <el-button @click="openRobotOrderCancel(scope.row.robot_id, scope.row.type)" type="text" size="small">{{$t('message.revoke')}}</el-button>
        <el-button @click="openRobotAssets(scope.row.robot_id, scope.row.type)" type="text" size="small">{{$t('message.asset-details')}}</el-button>
        <el-button @click="openRobotShoot(scope.row.symbol)" type="text" size="small">{{$t('message.asset-snapshot')}}</el-button>
      </template>
    </el-table-column>
  </el-table>
  <!--机器人添加界面-->
  <el-dialog
    :width="'30%'"
    :title="isEdit ? '编辑机器人' : '添加机器人'"
    :visible.sync="addRobotVisible">
    <el-form :label-position="labelPosition" label-width="130px">
      <el-form-item v-for="(item, key, idx) in formData" :key="idx" :label="item" class="form-item">
        <el-input v-model="formValues[key]" size="mini" class="item-input"></el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="submit"  :loading="addRobotLoading">{{$t('message.confirm')}}</el-button>
    </div>
  </el-dialog>
  <!--机器人详情-->
  <el-dialog
    :width="'30%'"
    title="机器人详情"
    :visible.sync="robotDetailVisible">
    <el-form :label-position="labelPosition" label-width="150px">
      <el-form-item v-for="(item, idx) in robotDetail" :key="idx" :label="item.label" class="form-item">
        <span>{{item.value}}</span>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button type="warning" @click="Edit">{{$t('message.edit')}}</el-button>
      <el-button type="primary" @click="robotDetailVisible">{{$t('message.confirm')}}</el-button>
    </div>
  </el-dialog>
  <!--机器人资金详情-->
  <el-dialog
    :title="$t('message.robot-asset-details')"
    :visible.sync="robotAssetsDetailVisible"
    width="60%">
    <el-table
      :data="assets"
      height="350"
      border
      style="width: 100%">
      <el-table-column
        prop="symbol"
        :label="$t('message.coin')">
      </el-table-column>
      <el-table-column
        prop="available"
        :label="$t('message.available-quantity')">
      </el-table-column>
      <el-table-column
        prop="freeze"
        :label="$t('message.frozen-quantity')">
      </el-table-column>
      <el-table-column
        prop="other_freeze"
        :label="$t('message.other-frozen')">
      </el-table-column>
      <el-table-column
        prop="recharge_status"
        :label="$t('message.recharge-status')">
        <template slot-scope="scope">
          <span>{{scope.row.recharge_status === 0 ? $t('message.no-recharge') : $t('message.rechargeable')}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="withdraw_fee"
        :label="$t('message.withdrawal-fee')">
      </el-table-column>
      <el-table-column
        prop="withdraw_max"
        :label="$t('message.max-withdrawal-amount')">
      </el-table-column>
      <el-table-column
        prop="withdraw_min"
        :label="$t('message.minimal-withdrawal-amount')">
      </el-table-column>
      <el-table-column
        prop="withdraw_status"
        :label="$t('message.withdraw-status')">
        <template slot-scope="scope">
          <span>{{scope.row.withdraw_status === 0 ? $t('message.no-withdrawable') : $t('message.mentioning-currency')}}</span>
        </template>
      </el-table-column>
    </el-table>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="robotAssetsDetailVisible = false">{{$t('message.close')}}</el-button>
    </div>
  </el-dialog>
  <!--机器人资金快照-->
  <el-dialog
    :title="$t('message.asset-snapshot')"
    :visible.sync="robotShootVisible"
    @closed="robotShootClose"
    width="90%">
    <div class="check-type" style="margin-bottom: 20px">
      <el-radio-group v-model="dateType" @change="changeDateType">
        <el-radio-button label="day"></el-radio-button>
        <el-radio-button label="week"></el-radio-button>
      </el-radio-group>
    </div>
    <snap-shoot-line></snap-shoot-line>
    <div slot="footer" class="dialog-footer">
      <el-button type="primary" @click="robotShootVisible = false">{{$t('message.close')}}</el-button>
    </div>
  </el-dialog>
</section>
</template>

<script>
import url from 'common/js/http'
import { strategyRobotList, robotDetail, modifyRobot, robotStart, robotStop, robotDelete, robotOrderCancel, robotAssets, strategySymbolList, strategyRobotParam, addStrategyRobot } from '../api/api'
import { haveEmpty } from 'common/js/util'
import SnapShootLine from 'components/snapShootLine'
import {mapActions, mapState} from 'vuex'

export default {
  data () {
    return {
      addRobotVisible: false,
      dataTableVisible: true,
      robotDetailVisible: false,
      robotShootVisible: false, //
      robotAssetsDetailVisible: false, //
      addRobotLoading: false,
      modifyRobotLoading: false,
      modifyRobotLoading2: false,
      mainDetailLoading: false,
      recDetailLoading: false,
      coinType: [],
      value: '',
      tableData: [],
      symbols: [],
      to_symbols: [],
      url: `${url}/robot/add`,
      formData: {},
      formValues: {},
      detailTitle: '',
      assets: [],
      dateType: 'day',
      labelPosition: 'left',
      robotDetail: [],
      isEdit: false,
      editId: ''
    }
  },
  created () {
    this.getRobot()
    strategySymbolList().then((res) => {
      console.log(res)
      if (res.data.code === 0) {
        this.coinType = res.data.symbols
      }
    })
  },
  beforeMount () {
    this.setModelList().then((res) => {
      console.log(res)
      this.modelList = res || []
    }).catch(() => {
      this.$message.error(this.$t('message.tip-11'))
    })
  },
  methods: {
    ...mapActions(['acSnapShoot', 'setRobotId', 'setModelList']),
    addRobot () {
      if (this.value === '') {
        this.$message.error(this.$t('请选择交易对'))
        return
      }
      strategyRobotParam({symbol: this.value}).then((res) => {
        console.log(res)
        if (res.data.code === 0) {
          this.formData = res.data.params
          const values = {}
          for (let k in res.data.params) {
            values[k] = ''
          }
          this.formValues = values
          this.formValues.self_symbol = this.value
          this.addRobotVisible = true
          this.isEdit = false
        }
      })
    },
    submit () {
      if (!haveEmpty(this.formValues)) {
        this.$message.error(this.$t('message.tip-15'))
      } else {
        this.$confirm(this.$t('message.tip-49'), this.$t('message.notification'), {
          confirmButtonText: this.$t('message.confirm'),
          cancelButtonText: this.$t('message.cancel'),
          type: 'warning'
        }).then(() => {
          const values = new FormData()
          const formValues = this.formValues
          for (let k in formValues) {
            values.append(k, formValues[k])
          }
          if (this.isEdit) {
            values.append('robotId', this.editId)
            values.append('type', 3)
            modifyRobot(values).then((res) => {
              console.log(res)
              if (res.data.code === 0) {
                this.addRobotVisible = false
                this.refreshRobotList()
                this.$message({
                  type: 'success',
                  message: '修改成功'
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.data.error
                })
              }
            }).catch(() => {
              this.$message({
                type: 'error',
                message: '修改失败'
              })
            })
          } else {
            addStrategyRobot(values).then((res) => {
              console.log(res)
              if (res.data.code === 0) {
                this.addRobotVisible = false
                this.refreshRobotList()
                this.$message({
                  type: 'success',
                  message: '添加成功'
                })
              } else {
                this.$message({
                  type: 'error',
                  message: res.data.error
                })
              }
            }).catch(() => {
              this.$message({
                type: 'error',
                message: '添加失败'
              })
            })
          }
        }).catch(() => {
          return false
        })
      }
    },
    openDetail (id, type, symbol) {
      this.editId = id
      robotDetail({robotId: id, type: type, symbol: symbol}).then((res) => {
        console.log(res)
        this.robotDetail = res.data.robot
        this.robotDetailVisible = true
      }).catch((err) => {
        console.log(err)
      })
    },
    openRobotStart (id, type, status) {
      let param = {robotId: id, type: type}
      if (status === '开启') {
        this.$confirm(this.$t('message.tip-18'), this.$t('message.notification'), {
          confirmButtonText: this.$t('message.confirm'),
          cancelButtonText: this.$t('message.cancel'),
          type: 'warning'
        }).then(() => {
          robotStop(param).then((res) => {
            console.log(res)
            if (res.data.code === 0) {
              this.refreshRobotList()
              this.$message({
                type: 'success',
                message: this.$t('message.tip-19')
              })
            } else {
              this.$message({
                type: 'error',
                message: res.data.error
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: this.$t('message.tip-20')
          })
        })
      } else {
        this.$confirm(this.$t('message.tip-21'), this.$t('message.notification'), {
          confirmButtonText: this.$t('message.confirm'),
          cancelButtonText: this.$t('message.cancel'),
          type: 'warning'
        }).then(() => {
          robotStart(param).then((res) => {
            console.log(res)
            if (res.data.code === 0) {
              this.refreshRobotList()
              this.$message({
                type: 'success',
                message: this.$t('message.tip-3')
              })
            } else {
              this.$message({
                type: 'error',
                message: res.data.error
              })
            }
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: this.$t('message.tip-4')
          })
        })
      }
    },
    openRobotDelete (id, type) {
      let param = {robotId: id, type: type}
      this.$confirm(this.$t('message.tip-22'), this.$t('message.notification'), {
        confirmButtonText: this.$t('message.confirm'),
        cancelButtonText: this.$t('message.cancel'),
        type: 'warning'
      }).then(() => {
        robotDelete(param).then((res) => {
          console.log(res)
          if (res.data.code === 0) {
            this.refreshRobotList()
            this.$message({
              type: 'success',
              message: this.$t('message.tip-5')
            })
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('message.tip-4')
        })
      })
    },
    openRobotOrderCancel (id, type) {
      let param = {robotId: id, type: type}
      this.$confirm(this.$t('message.tip-6'), this.$t('message.notification'), {
        confirmButtonText: this.$t('message.confirm'),
        cancelButtonText: this.$t('message.cancel'),
        type: 'warning'
      }).then(() => {
        robotOrderCancel(param).then((res) => {
          console.log(res)
          if (res.data.code === 0) {
            this.refreshRobotList()
            this.$message({
              type: 'success',
              message: this.$t('message.tip-8')
            })
          }
        }).catch(() => {
          this.$message({
            type: 'error',
            message: this.$t('message.tip-23')
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: this.$t('message.tip-7')
        })
      })
    },
    openRobotAssets (id, type) {
      let param = {robotId: id, type: type}
      this.robotAssetsDetailVisible = true
      robotAssets(param).then((res) => {
        console.log(res)
        if (res.data.code === 0) {
          let obj = JSON.parse(res.data.user_assets)
          let arrTemp = obj.result
          let arr = []
          for (let idx in arrTemp) {
            console.log(idx)
            if (idx !== 'user_id') {
              arrTemp[idx].symbol = idx
              arr.push(arrTemp[idx])
            }
          }
          console.log(arr)
          this.assets = arr
        }
      })
    },
    openRobotShoot (symbol) {
      this.robotShootVisible = true
      this.checkedSybol = symbol
      let nowDate = new Date()
      let end = Date.parse(nowDate) / 1000
      let start = end - 24 * 3600
      let param = {selfSymbol: symbol, type: this.dateType, startTime: start, endTime: end}
      this.acSnapShoot({param, day: 'day'})
    },
    robotShootClose () {
      this.dateType = 'day'
    },
    changeDateType (val) {
      // console.log(val)
      let nowDate = new Date()
      let end = Date.parse(nowDate) / 1000
      // let start = new Date(nowDate - 7 * 24 * 3600 * 1000).getTime() / 1000
      let start = val === 'day' ? end - 24 * 3600 : end - 7 * 24 * 3600
      // let start = end - 7 * 24 * 3600
      let param = {selfSymbol: this.checkedSybol, type: val, startTime: start, endTime: end}
      this.acSnapShoot({param, val})
    },
    refreshRobotList () {
      this.dataTableVisible = true
      this.getRobot()
    },
    getRobot () {
      strategyRobotList().then((res) => {
        console.log(res)
        if (res.data.code && res.data.code !== 0) {
          this.$message.error(this.$t('message.tip-10'))
          return
        }
        this.tableData = res.data.robots
        this.dataTableVisible = false
      }).catch(() => {
        this.$message.error(this.$t('message.tip-10'))
      })
    },
    Edit () {
      const forData = {}
      this.robotDetail.forEach((item) => {
        forData[item.key] = item.label
        this.formValues[item.key] = item.value
      })
      this.formData = forData
      this.isEdit = true
      this.robotDetailVisible = false
      this.addRobotVisible = true
    }
  },
  computed: {
    ...mapState(['robot_id']),
    isTest () {
      return window.location.hostname === '47.91.238.88'
    },
    userLevel () {
      return localStorage.getItem('userLevel')
    }
  },
  components: {
    SnapShootLine
  }
}

</script>

<style scoped lang="scss">
  .form-item {
    margin-bottom: 0;
    .item-input {
      width: 250px;
    }
  }
  .dataTitle {
    margin: 10px auto;
    width: 600px;
  }
  .detailTable {
    margin: auto;
    width: 601px;
    border-collapse:collapse;
    border: 1px solid #dfe6ec;
    tr {
      td {
        overflow: hidden;
        word-break:break-all;
        width: 150px;
        height: 40px;
        padding: 5px;
        border: 1px solid #dfe6ec;
        text-align: center;
        span {
          font-size: 12px;
        }
        input {
          text-align: center;
          padding: 0 5px;
          width: 150px;
          height: 40px;
          border: none;
          &:disabled {
            background: #fff;
          }
        }
      }
      td:nth-child(1), td:nth-child(3), td:nth-child(5) {
        background: #eef1f6;
      }
    }
  }
  .detailTable2 {
    width: 100%;
    margin: 0 0 10px 0;
  }
  .dialog-footer {
    text-align: center;
    padding: 20px 50px 0 0;
  }
  .inp {
    text-align: center;
    padding: 0 5px;
    width: 75px;
    height: 40px;
    border: none;
    &:disabled {
      background: #fff;
    }
  }
  .option-btns {
    display: flex;
    justify-content: flex-end;
    button {
      margin: 10px 10px;
    }
  }
</style>
